/**
 * create by zhangpu
 * date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.webank.marshall;

import com.google.common.collect.Maps;

import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.webank.domain.WeBankResponse;
import com.acooly.module.openapi.client.provider.webank.partner.WeBankKeyPairManager;
import com.acooly.module.safety.Safes;
import com.acooly.module.safety.signature.SignTypeEnum;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Map;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import static com.acooly.module.openapi.client.provider.webank.utils.MapHelper.mapToBean;

/**
 * @author zhangpu
 */
@Slf4j
@Service
public class WeBankResponseUnmarshall extends WeBankMarshallSupport implements ApiUnmarshal<WeBankResponse, String> {

    private static final Logger logger = LoggerFactory.getLogger(WeBankResponseUnmarshall.class);

    @Resource(name = "weBankMessageFactory")
    private MessageFactory messageFactory;

    @Resource(name = "weBankGetKeyPairManager")
    private WeBankKeyPairManager keyPairManager;

    @SuppressWarnings("unchecked")
    @Override
    public WeBankResponse unmarshal(String message, String serviceName) {
        try {
            logger.info("响应报文:{}", message);

            String[] tempArray = message.split ("&signature=");
            String plain = tempArray[0];
            String sign = tempArray[1];
            logger.info ("代签名串：{}", plain);
            logger.info ("签名字符串{}", sign);

            WeBankResponse weBankResponse = (WeBankResponse) messageFactory.getResponse (serviceName);
            //解析返回的报文
            Map<String, Object>  resMap = parseBody(plain);
            mapToBean(resMap,weBankResponse);
            weBankResponse.setPartnerId(resMap.get("merId").toString());
            weBankResponse.setSign(sign);
            weBankResponse.setBizType(serviceName);
            //签名处理
            Safes.getSigner(SignTypeEnum.Rsa.name ()).verify(plain, keyPairManager.getKeyPair(weBankResponse.getPartnerId()), sign);
            return weBankResponse;
        } catch (Exception e) {
            throw new ApiClientException("解析响应报文错误:" + e.getMessage());
        }
    }


    public static Map<String, Object> parseBody (String body) {
        if (StringUtils.isBlank (body)) {
            return null;
        }
        Map<String, Object> resultMap = Maps.newHashMap ();
        // body  merId=xx&orderId=xx&bizType=xx&respCode=xx&respMsg=xx
        String[] strs = body.split ("&");
        for (String s : strs) {
            String[] ms = s.split ("=");
            if (ms.length < 2){
                resultMap.put (ms[0],"");
            }else{
                resultMap.put (ms[0], ms[1]);
            }
        }
        return resultMap;
    }
}
